<template>
  <LoginTemplate :title="route.name == 'login' ? 'AIP' : t('login', 'AIP项目管理平台')"
		:callBack='handleSubmit'
    v-if="!(state?.userInfo?.remember && state?.userInfo?.token)"
	>
    <a-form
      ref="formRef"
      :rules="rules"
      :model="formState"
      class="loginForm"
    >
      <a-form-item has-feedback name="num">
        <a-input
          style="height: 40px"
          v-model:value="formState.num"
          :placeholder="t('login', '请输入账号')"
        >
          <template #prefix>
            <UserOutlined class="siteFormItemIcon" />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item has-feedback name="password">
        <a-input-password
          style="height: 40px"
          v-model:value="formState.password"
          :placeholder="t('login', '请输入密码')"
        >
          <template #prefix>
            <LockOutlined class="siteFormItemIcon" />
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item has-feedback name="code">
        <div style="display: flex">
          <a-input v-model:value="formState.code" :placeholder="t('login', '请输入验证码')" />
          <img
            style="height: 40px; border-radius: 6px; margin-left: 10px"
            :src="formState.imageCaptcha"
            @click="imageShow"
          />
        </div>
      </a-form-item>
			<a-form-item :label="t('login', '角色')">
			      <a-radio-group v-model:value="formState.identity">
			        <a-radio value="student">{{ t('login', '学生') }}</a-radio>
			        <a-radio value="teacher">{{ t('login', '教师') }}</a-radio>
			      </a-radio-group>
			    </a-form-item>
      <a-form-item>
        <a-checkbox v-model:checked="formState.remember">{{t('login', '自动登录')}}</a-checkbox>
        <a class="loginFormSign" style="float: right" @click="forget"
          >{{t('login', '忘记密码')}}</a
        >
      </a-form-item>
			
			<a-form-item class="buttonBox">
        <a-button :loading="btnLoading" :disabled="btnDisabled" type="primary" style="width: 340px;height: 40px;" @click.prevent="handleSubmit">
          {{t('login', '登录')}}
        </a-button>
      </a-form-item>
    </a-form>
  </LoginTemplate>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { setUserInfo, state } from '@/stores/info.js'

import { reactive, computed, watchEffect, ref } from 'vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import {
  loginCaptchaStudent,
  loginStudent,
} from '@/request/login.js'
import { message } from 'ant-design-vue'
import LoginTemplate from './components/LoginTemplate.vue'
import { Modal } from 'ant-design-vue'
import { h } from 'vue'
import { t, changeLangNoRefresh } from '@/i18n'
const rules = {
  num: [
    {
      required: true,
      message: t('login', '请输入账号'),
      trigger: 'change',
    },
  ],
  password: [
    { required: true, message: t('login', '请输入密码'), trigger: 'change' },
    { min: 6, max: 16, message: t('login', '密码长度必须在6-16位之间') },
    // { pattern: /^[A-Za-z0-9]{6,16}$/, message: '密码必须是6-16位的字母或数字' },
  ],
  code: [
    {
      required: true,
      message: t('login', '请输入验证码'),
      trigger: 'change',
    },
  ],
	identity:[
    {
      required: true,
			default:'student',
      message: t('login', '请选择角色'),
      trigger: 'change',
    },
  ],
}
const formRef = ref()
const formState = reactive({
	identity:'student'
})

const route = useRoute()
const router = useRouter()

const btnDisabled = computed(
  () =>
    !(
      formState.num &&
      formState.password &&
      formState.code &&
      formState.codeId&&
			formState.identity
    )
)
const btnLoading = ref(false)
//弹出忘记密码框
const forget = () => {
  Modal.warning({
    title: t('login', '通知'),
    content: h('div', {}, [
      h('p', t('login', '需要联系相关老师重置密码')),
      // h('p', '可钉钉联系张会斌老师或杨佳策老师'),
    ]),
    onOk() {
      console.log('ok')
    },
  })
}

const show = () => {
  if (state?.userInfo?.remember && state?.userInfo?.token) {
    switch (route.name) {
      case 'login':
      case 'NotFound':
        if (state?.userInfo?.identity == 'teacher') return router.replace({name: 'teacher'})
        router.replace({name: 'stu'})
        break
    }
  }
}
const imageShow = async () => {
  let res = await loginCaptchaStudent()
  console.log(res, 'res')
  if (!res) return
  const blob = new Blob([res?.data], { type: 'application/octet-stream' })
  const url = window.URL.createObjectURL(blob)
  formState.imageCaptcha = url
  formState.codeId = res?.headers?.id
}
imageShow()
show()
const handleSubmit = async () => {
  let v = await formRef.value.validate().catch(err => false)
	if (!v) return
	btnLoading.value = true
	let res = null
	// formState.mobile=formState.num
  res = await loginStudent(formState)
	btnLoading.value = false
	// setTimeout(() => { btnLoading.value = false }, 500 + Math.random()*500)
	if(res&&res.code==200){
     setUserInfo(res.data)
     changeLangNoRefresh(res.data.language)
		if(res.data.isDefaultPassword){
      router.push({name: 'FirstChange',query:{home:'stu',login:'login'}})
			return
		}
	}
	if (!res) return imageShow()
      formState.identity == 'student' ? router.push({name: 'stu'}) : router.push({name: 'teacher'})
	
}
</script>

<style lang="scss" scoped>
@import '../../styles/public.scss';

.loginForm {
  .accept {
    font-size: 12px;
  }

  .buttonBox {
    @include FlexCenterAndCenter;
    width: 100%;

    .loginFormButton {
      width: 320px;
    }
  }
}
</style>
